const configCenter = require("uni-config-center");
const crypto = require("crypto");
const config = configCenter({
	pluginId: 'vk-unicloud'
}).requireFile('index.js');

function objKeySort(arys, partner_key) {
	//先用Object内置类的keys方法获取要排序对象的属性名数组，再利用Array的sort方法进行排序 
	var newkey = Object.keys(arys).sort();
	console.log('newkey=' + newkey);
	var newObj = '';
	//建立一个新的对象，用于存放排好序的键值对 
	for (var i = 0; i < newkey.length; i++) { //遍历newkey数组 
		newObj += [newkey[i]] + '=' + arys[newkey[i]] + '&';
	}
	return newObj.substring(0, newObj.length - 1) + '&partner_key=' + partner_key;
}

module.exports = {
	/**
	 * 数据删除
	 * @url admin/kong/sys/delete 前端调用的url参数地址
	 * data 请求参数 说明
	 * res 返回参数说明
	 * @param {Number} code 错误码，0表示成功
	 * @param {String} msg 详细信息
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid
		} = data;
		let res = {
			code: 0,
			msg: 'ok'
		};
		// 业务逻辑开始-----------------------------------------------------------

		const {
			baijiayun
		} = config.vk;
		let {
			_id
		} = data;
		if (vk.pubfn.isNull(_id)) {
			return {
				code: -1,
				msg: 'id不能为空'
			};


			let room = await vk.baseDao.findById({
				dbName,
				id: _id
			});

			let private_domain = baijiayun.private_domain
			var baijiayunParmas = {
				partner_id: baijiayun.Partner_ID,
				room_id: room.room_id,
				timestamp: Date.now() / 1000
			}
			let str = objKeySort(baijiayunParmas, baijiayun.Partner_Key)
			console.log(str)
			let sign = crypto
				.createHash('md5')
				.update(str, 'utf-8')
				.digest('hex').toLowerCase()
			baijiayunParmas.sign = sign

			console.log(baijiayunParmas)
			let requestRes = await vk.request({
				url: `https://${private_domain}.at.baijiayun.com/openapi/room/update`,
				method: "POST",
				data: baijiayunParmas,
				useContent: false, // 是否需要将data请求参数转成body请求体
			});
			console.log(requestRes)
			if (requestRes.code != 0) {
				return {
					code: requestRes.code,
					msg: requestRes.msg
				}
			}
		}
		let dbName = "live_course_videos";
		await vk.baseDao.deleteById({
			dbName,
			id: _id
		});
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}

}
